<template>
	<view class="order-container">
		<!-- 顶部搜索栏 -->
		<view class="header">
			<view class="header-content">
				<view class="search-container">
					<view class="search-box">
						<image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
						<input type="text" placeholder="搜索订单号" v-model="searchKeyword" class="search-input"
							placeholder-class="search-placeholder" @input="onSearchInput" />
					</view>

					<view class="search-btn" @click="handleSearch">
						<text class="search-btn-text">搜索</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 分类标签 -->
		<view class="category-tabs" :style="{ marginTop: (statusBarHeight + navBarHeight) + 'px' }">
			<view v-for="(category, index) in categories" :key="index" class="category-item"
				:class="[activeCategory === index ? 'active' : '']" @click="switchCategory(index)">
				<text class="category-text">{{ category.name }}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y="true" @scrolltolower="loadMore" :lower-threshold="100"
			:enable-back-to-top="true">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 空状态 -->
			<view v-else-if="orderList.length === 0" class="empty-state">
				<image src="/static/image/empty_order.png" class="empty-icon" mode="aspectFit"></image>
				<text class="empty-text">暂无订单</text>
				<text class="empty-desc">快去下单吧~</text>
			</view>

			<!-- 订单列表 -->
			<view v-else class="order-list-container">
				<view v-for="(order, index) in orderList" :key="order.id" class="order-item">
					<!-- 订单头部 -->
					<view class="order-header">
						<view class="order-number">
							<text class="order-number-text">订单号 {{ order.order_no }}</text>
							<text class="copy-btn" @click="copyOrderNumber(order.order_no)">复制</text>
						</view>
						<view class="order-status" :class="[getStatusClass(order.status)]">
							<text class="status-text">{{ getStatusText(order.status) }}</text>
						</view>
					</view>

					<!-- 订单信息 -->
					<view class="order-product" v-for="item in order.orderItems" @click="viewOrderDetail(order)">
						<image :src="item.product_cover" class="product-image" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-title">{{ item.product_name }}</text>
							<text class="product-desc">{{ getOrderDesc(item.sku_spec) }}</text>
							<text class="order-time">{{ formatTime(order.create_time) }}</text>
						</view>
						<view class="product-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ order.amount || '0.00' }}</text>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="order-actions">
						<view v-if="order.status === 'pending'" class="action-btn primary" @click="payOrder(order)">
							<text class="action-text">支付</text>
						</view>
						<view v-else-if="order.status === 'shipped'" class="action-btn primary"
							@click="confirmReceipt(order)">
							<text class="action-text">确认收货</text>
						</view>
						<!-- <view v-else-if="order.status === 'completed'" class="action-btn secondary"
							@click="writeReview(order)">
							<text class="action-text">评价</text>
						</view> -->
						<!-- <view v-else-if="order.status === 'paid'" class="action-btn secondary"
							@click="createRefund(order)">
							<text class="action-text">申请退款</text>
						</view> -->

						<!-- 通用操作按钮 -->
						<view class="action-btn secondary" @click="viewOrderDetail(order)">
							<text class="action-text">订单详情</text>
						</view>

						<view v-if="order.status === 'pending' || order.status === 'pending_pricing'"
							class="action-btn secondary" @click="cancelOrder(order)">
							<text class="action-text">取消订单</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多状态 -->
			<view v-if="loading && orderList.length > 0" class="load-more">
				<text class="load-more-text">加载中...</text>
			</view>
			<view v-else-if="!hasMore && orderList.length > 0" class="no-more">
				<text class="no-more-text">没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>
<script>
import {
	ORDER_STATUS
} from "../../utils/enum.js";

export default {
	data() {
		return {
			statusBarHeight: 0,
			navBarHeight: 0,
			searchKeyword: '',
			activeCategory: 0,
			hasMore: true,
			loading: false,
			currentPage: 1,
			categories: [
				// {
				// 	name: '全部',
				// 	status: ''
				// },
				{
					name: '待支付',
					status: ORDER_STATUS.PENDING
				},
				{
					name: '待收货',
					status: ORDER_STATUS.SHIPPED
				},
				{
					name: '已完成',
					status: ORDER_STATUS.COMPLETED
				},
				{
					name: '退款中',
					status: ORDER_STATUS.REFUNDING
				},
				{
					name: '已退款',
					status: ORDER_STATUS.REFUNDED
				},
				{
					name: '已取消',
					status: ORDER_STATUS.CANCELLED
				}
			],
			orderList: []
		}
	},
	methods: {
		// 获取系统信息
		getSystemInfo() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;

			if (uni.getMenuButtonBoundingClientRect) {
				const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
				this.navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - this.statusBarHeight) * 2;
			} else {
				this.navBarHeight = 44;
			}
		},

		// 搜索输入
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;
		},

		// 执行搜索
		handleSearch() {
			uni.showLoading({
			});

			// 重置页码并搜索
			this.currentPage = 1;
			
			// 调用API获取订单列表
			this.loadOrderList();
		},

		// 切换分类
		switchCategory(index) {
			this.activeCategory = index;
			this.orderList = [];
			uni.showLoading({
				title: '加载中...'
			});

			// 重置页码
			this.currentPage = 1;

			// 调用API获取订单列表
			this.loadOrderList();
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'pending_pricing': '待定价',
				'pending': '待付款',
				'paid': '已付款',
				'shipped': '待收货',
				'completed': '已完成',
				'cancelled': '已取消',
				'refunding': '退款中',
				'refunded': '已退款'
			};
			return statusMap[status] || '未知状态';
		},

		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				'pending_pricing': 'status-pending-pricing',
				'pending': 'status-pending',
				'paid': 'status-paid',
				'shipped': 'status-shipped',
				'pending_receipt': 'status-pending-receipt',
				'completed': 'status-completed',
				'cancelled': 'status-cancelled',
				'refunding': 'status-refunding',
				'refunded': 'status-refunded'
			};
			return classMap[status] || 'status-unknown';
		},

		// 复制订单号
		copyOrderNumber(orderNo) {
			uni.setClipboardData({
				data: orderNo,
				success: () => {
					uni.showToast({
						title: '订单号已复制',
						icon: 'success'
					});
				}
			});
		},
		// 查看订单详情
		viewOrderDetail(order) {
			uni.navigateTo({
				url: `/pages/order/detail?id=${order.id}`
			});
		},

		// 支付订单
		payOrder(order) {
			uni.showModal({
				title: '确认支付',
				content: `确认支付订单 ${order.order_no}？金额：¥${order.amount || '0.00'}`,
				success: (res) => {
					if (res.confirm) {
						this.getPay(order.id)
					}
				}
			});
		},
		getPay(order_id) {
			uni.showLoading({
				title: '微信支付请求'
			});
			const that = this
			this.$api.createPay({
				order_id
			}).then(payment => {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payment.timestamp,
					nonceStr: payment.nonce_str,
					package: payment.package,
					signType: payment.signType,
					paySign: payment.paySign,
					success: (result) => {
						uni.showToast({
							title: '支付成功'
						});

						// 刷新订单状态
						that.refreshOrderStatus(order_id, 'paid');
					},
					fail: (result) => {
						uni.showToast({
							icon: 'none',
							title: '支付失败',
						});
					},
					complete: () => {

					}
				});
			})
		},
		// 确认收货
		confirmReceipt(order) {
			uni.showModal({
				title: '确认',
				content: '确认收货？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '确认中...'
						});

						// 调用确认收货接口
						const confirmData = {
							id: order.id,
						};
						this.$api.confirmOrderComplete(confirmData).then(res => {
							uni.hideLoading();
							uni.showToast({
								title: '确认成功',
								icon: 'success'
							});
							this.refreshOrderStatus(order.id, 'completed');
						})
					}
				}
			});

		},

		// 申请退款
		createRefund(order) {
			uni.showModal({
				title: '申请退款',
				content: '确认申请退款？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '退款中...'
						});
						this.$api.createOrderRefund({ id: order.id, refund_reason: '用户申请退款' }).then(res => {
							uni.hideLoading();
							uni.showLoading({
								title: '退款中...'
							});
							this.$api.confirmTravelOrderRefund({
								id: order.id,
								refund_remark: '用户申请退款',
								refund_amount: order.payment_amount,
								approve: true
							}).then(res => {
								uni.hideLoading();
								uni.showToast({
									title: '退款申请成功',
									icon: 'success'
								});
								this.refreshOrderStatus(order.id, 'refunding');
							})
						})
					}
				}
			});
		},

		// 查看物流
		viewLogistics(order) {
			uni.navigateTo({
				url: `/pages/order/logistics?id=${order.id}`
			});
		},

		// 写评价
		writeReview(order) {
			uni.navigateTo({
				url: `/pages/order/comment?id=${order.id}`
			});
		},

		// 查看退款详情
		viewRefund(order) {
			uni.navigateTo({
				url: `/pages/order/refund?id=${order.id}`
			});
		},

		// 取消订单
		cancelOrder(order) {
			uni.showModal({
				title: '取消订单',
				content: '确认取消该订单？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '取消中...'
						});

						// 调用取消订单接口
						const cancelData = {
							id: order.id,
							user_id: this.userInfo.id
						};

						this.$api.cancelOrder(cancelData).then(res => {
							uni.hideLoading();
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							// 刷新订单状态
							this.refreshOrderStatus(order.id, 'cancelled');
						})
					}
				}
			});
		},

		// 刷新订单状态
		refreshOrderStatus(orderId, newStatus) {
			const orderIndex = this.orderList.findIndex(order => order.id === orderId);
			if (orderIndex !== -1) {
				this.orderList[orderIndex].status = newStatus;
			}
		},

		// 下拉刷新
		onRefresh() {
			uni.showLoading({
				title: '刷新中...'
			});

			// 重新加载订单列表
			this.loadOrderList();
		},

		// 加载更多
		loadMore() {
			if (!this.hasMore || this.loading) return;

			this.loading = true;

			// 计算下一页
			this.currentPage += 1;
			// 调用API获取订单列表
			this.loadOrderList();
		},
		// 获取订单描述
		getOrderDesc(sku_spec) {
			let _sku_spec = JSON.parse(sku_spec)
			let desc = ''
			if (_sku_spec) {
				for (let key in _sku_spec) {
					desc += `${_sku_spec[key]} `
				}
			}
			return desc
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '';
			const date = new Date(timeStr);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},

		// 初始化数据
		initData() {
			this.currentPage = 1
			this.orderList = []
			this.loading = true;
			uni.showLoading({
				title: '加载中...'
			});

			// 调用API获取订单列表
			this.loadOrderList();
		},

		// 加载订单列表
		loadOrderList() {
			const params = {
				user_id: this.userInfo.id,
				pageNo: this.currentPage,
				pageSize: 10,
				order_no: this.searchKeyword.trim()
			};
			// 如果有状态筛选，添加状态参数
			const currentStatus = this.categories[this.activeCategory].status;
			console.log('currentStatus',currentStatus)
			if (currentStatus) {
				params.status = currentStatus;
			}

			this.$api.getOrderList(params).then(res => {
				this.loading = false;
				uni.hideLoading();

				if (res && res.list) {
					this.orderList =[
						...this.orderList,
						...res.list
					]
					this.hasMore = this.orderList.length < res.total;
				}
			})
		}
	},
	onShow() {
		this.initData();
		// this.getSystemInfo();
	}
}
</script>

<style lang="scss">
.order-container {
	height: 100vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
}

// 顶部搜索栏
.header {
	//position: fixed;
	//top: 0;
	//left: 0;
	//right: 0;
	//z-index: 1000;
	background-color: #fff;
	//padding-right: 140rpx;
	padding: 24rpx 32rpx;

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search-container {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-right: 20rpx;

		.search-box {
			flex: 1;
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			padding: 0 24rpx;
			height: 72rpx;
			border: 2rpx solid #A6A6A6;
			position: relative;

			.search-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 16rpx;
			}

			.search-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
			}

			.search-placeholder {
				color: #999;
			}
		}

		.search-btn {
			color: #333;

			.search-btn-text {
				font-size: 28rpx;
			}

			&:active {
				background-color: #555;
			}
		}
	}
}

// 分类标签
.category-tabs {
	display: flex;
	align-items: center;
	padding: 24rpx 32rpx;
	background-color: #fff;
	gap: 40rpx;
	border-bottom: 2rpx solid #f0f0f0;
	overflow-x: auto;

	.category-item {
		flex-shrink: 0;
		position: relative;
		padding-bottom: 16rpx;

		.category-text {
			font-size: 28rpx;
			color: #666;
			font-weight: 400;
		}

		&.active {
			.category-text {
				color: #333;
				font-weight: 500;
			}

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 4rpx;
				background-color: #FFC300;
				border-radius: 2rpx;
			}
		}

		&:active {
			opacity: 0.7;
		}
	}
}

// 订单列表
.order-list {
	flex-grow: 1;
	padding-top: 24rpx;
	width: 100%;
	box-sizing: border-box;
	overflow: hidden;
}

// 加载状态
.loading-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 120rpx 32rpx;

	.loading-text {
		font-size: 28rpx;
		color: #999;
	}
}

// 空状态
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 32rpx;

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 32rpx;
		opacity: 0.6;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 16rpx;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #ccc;
	}
}

.order-list-container {
	padding: 0 32rpx;
}

.order-item {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 24rpx;
	overflow: hidden;
}

// 订单头部
.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;

	.order-number {
		display: flex;
		align-items: center;
		gap: 12rpx;

		.order-number-text {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.copy-btn {
			font-size: 24rpx;
			color: #333;
			padding: 4rpx 8rpx;
			border-radius: 4rpx;
			background-color: rgba(255, 107, 53, 0.1);

			&:active {
				background-color: rgba(255, 107, 53, 0.2);
			}
		}
	}

	.order-status {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;

		&.status-pending-pricing {
			background-color: #e3f2fd;
			color: #2196f3;
		}

		&.status-pending {

			background-color: #ffebee;
			color: #f44336;
		}

		&.status-paid {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-shipped {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-pending-receipt {
			background-color: #fff8e1;
			color: #ff9800;
		}

		&.status-completed {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-cancelled {
			background-color: #f5f5f5;
			color: #999;
		}

		&.status-refunding {
			background-color: #ffebee;
			color: #f44336;
		}

		&.status-refunded {
			background-color: #f5f5f5;
			color: #999;
		}

		.status-text {
			font-weight: 500;
		}
	}
}

// 商品信息
.order-product {
	display: flex;
	align-items: center;
	padding: 24rpx 32rpx;
	gap: 20rpx;

	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.product-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			line-height: 1.4;
		}

		.product-desc {
			font-size: 24rpx;
			color: #666;
		}

		.order-time {
			font-size: 22rpx;
			color: #999;
			margin-top: 4rpx;
		}
	}

	.product-price {
		display: flex;
		align-items: baseline;
		gap: 4rpx;

		.price-symbol {
			font-size: 24rpx;
			color: #333;
		}

		.price-value {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
		}
	}
}

// 操作按钮
.order-actions {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	gap: 16rpx;
	padding: 24rpx 32rpx;
	border-top: 1rpx solid #f0f0f0;

	.action-btn {
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;

		&.primary {
			background-color: #FFC300;
			color: #333;

			&:active {
				background-color: #e55a2b;
			}
		}

		&.secondary {
			background-color: #f5f5f5;
			color: #666;

			&:active {
				background-color: #e8e8e8;
			}
		}

		.action-text {
			font-size: 26rpx;
		}
	}
}

// 加载更多
.load-more {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80rpx;
	margin: 20rpx 0;
	padding: 20rpx;

	.load-more-text {
		font-size: 26rpx;
		color: #999;
	}
}

.no-more {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 60rpx;
	margin: 20rpx 0;
	padding: 20rpx;

	.no-more-text {
		font-size: 24rpx;
		color: #ccc;
	}
}
</style>
